﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DrugStore.Exceptions;
using DrugStore.Helper;
using System.IO;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;

namespace DrugStore.Models
{
    public class NewModels
    {
        public String NewsId { get; set; }
        [Required(ErrorMessage = "Tiêu đề là bắt buộc")]
        [DisplayName("Tiêu đề: ")]
        public String Name { get; set; }
        [Required(ErrorMessage = "Nội dung là bắt buộc")]
        [DisplayName("Nội dung: ")]
        public String Content { get; set; }
        [Required(ErrorMessage = "Ảnh đại diện là bắt buộc")]
        [DisplayName("Ảnh đại diện: ")]
        public String ImagePath { get; set; }        
        public int Status { get; set; }
        public DateTime DateCreate { get; set; }

        public NewModels(News news) {
            NewsId = news.NewsId.ToString();
            Name = news.Title;
            Content = news.Containts;
            ImagePath = news.ImagePath;
            Status = news.Status;
            DateCreate = (DateTime)news.DateCreate;                            
        }
    }

    #region Bussiness
    public class NewBussiness
    {
        DrugStoreEntities entities;
        public PaginateList<News> GetAllNews(int pageIndex,int pageSize) 
        {
            entities = new DrugStoreEntities();
            var source = entities.News.OrderBy(n=>n.DateCreate);
            PaginateList<News> news = new PaginateList<News>(source, pageIndex, pageSize,null,null,null,null);
            return news;            
        }
        public IQueryable<News> GetAllNews() {
            entities = new DrugStoreEntities();
            return entities.News.OrderBy(n=>n.DateCreate);
        }

        public News GetMedicalNew()
        {
            entities = new DrugStoreEntities();
            Category category = entities.Categories.FirstOrDefault(n => n.Name.Equals("Y học cổ truyền", StringComparison.OrdinalIgnoreCase));
            if (category == null) 
            {
                return null;
            }
            if(category != null){
                var medicalNews = category.News.OrderBy(n => n.DateCreate).Take(3);
                if (medicalNews == null) {
                    return null;
                }
                if (medicalNews.Count() == 0)
                {
                    return null;
                }

                News lastesNew = (News)medicalNews.FirstOrDefault();
                String []temp = lastesNew.Containts.Split(' ');
                String briefContents = temp.Take(10).ToString();
                lastesNew.Containts = briefContents;
                return lastesNew;
            }
            return null;
        }

        public News GetHealthNew()
        {
            entities = new DrugStoreEntities();
            Category category = entities.Categories.FirstOrDefault(n => n.Name.Equals("Sức khỏe", StringComparison.OrdinalIgnoreCase));
            if (category == null) 
            {
                return null;
            }
            var healthyNews = category.News.OrderBy(n => n.DateCreate).Take(3);
            if (healthyNews.Count() == 0) 
            {
                return null;
            }
            News lastesNew = (News)healthyNews.FirstOrDefault();
            String[] temp = lastesNew.Containts.Split(' ');
            String briefContents = temp.Take(10).ToString();
            lastesNew.Containts = briefContents;
            return lastesNew;
        }
        
        public IQueryable<News> GetMedicalNews() 
        {
            entities = new DrugStoreEntities();
            Category category = entities.Categories.FirstOrDefault(n => n.Name.Equals("Y học cổ truyền", StringComparison.OrdinalIgnoreCase));
            if (category == null)
            {
                return null;
            }
            var medicalNews = category.News.OrderBy(n=>n.DateCreate).AsQueryable();            
            return medicalNews;
        }
        
        public IQueryable<News> GetHealthNews() 
        {
            entities = new DrugStoreEntities();
            Category category = entities.Categories.FirstOrDefault(n => n.Name.Equals("Sức khỏe", StringComparison.OrdinalIgnoreCase));
            if (category == null)
            {
                return null;
            }
            var healthCategory = category.News.OrderBy(n => n.DateCreate).AsQueryable();
            return healthCategory;
        }

        public NewModels GetNewById(String id) {
            entities = new DrugStoreEntities();
            Guid newId = new Guid(id);

            News temp = new News();
            temp = entities.News.FirstOrDefault(n => n.NewsId == newId);
            if (temp == null) {
                throw new ParameterInvalidException("Null","Don't exist new");            
            }
            NewModels objNew = new NewModels(temp);
            return objNew;
        }

        /*Get News object by newId
         * name: GetNewsById
         * parameter: newId type:String         
         */
        public News GetNewsById(String id) 
        {
            entities = new DrugStoreEntities();
            //Create guid object
            Guid newId = new Guid();            
            //If don't convert id to Guid type.
            if(!Guid.TryParse(id,out newId))
            {
                throw new ParameterInvalidException("NUll", "Don't find the properly object");
            }
            //Create a News Object
            News temp = new News();           
            temp = entities.News.FirstOrDefault(n=>n.NewsId.Equals(newId));
            
            //If don't find any properly News Object.
            //Throws exception.
            if (temp == null) 
            {
                throw new ParameterInvalidException("Null","Don't exist new");
            }

            //return object for the function.
            return temp;
        }

        public void AddNews(ManageNewModel model) 
        {
            DrugStoreEntities entities = new DrugStoreEntities();
            News news = new News();
            news.NewsId = Guid.NewGuid();
            news.Title = model.Title;
            news.Status = 1;
            news.DateCreate = DateTime.Now;
            news.ViewNumber = 0;
            news.Containts = model.Content;
            news.ImagePath = model.ImagePath;
            //ManageNewBusiness mnBusiness = new ManageNewBusiness();
            
            foreach (String c in model.SelectedCategories)
            {
                Guid id;
                Guid.TryParse(c, out id);
                if (id != null)
                {
                    Category category = entities.Categories.FirstOrDefault(cat => cat.CategoryId == id);
                    if (category != null)
                    {
                        news.Categories.Add(category);
                    }
                }
            }
            entities.News.AddObject(news);
            entities.SaveChanges();
        }

        public void UpdateNews(ManageNewModel model) 
        {
            DrugStoreEntities entities = new DrugStoreEntities();
            Guid newId = Guid.Empty;
            if (!Guid.TryParse(model.NewsId, out newId)) 
            {
                throw new Exception("Tin này không tồn tại");
            }
            News  news = entities.News.FirstOrDefault(n=>n.NewsId == newId);
            if(news == null)
            {
                throw new Exception("Tin này không tồn tại");
            }

            //Guid categoryID = Guid.Empty;
            //if(!Guid.TryParse(model.categoryId,out categoryID));
            news.Title = model.Title;
            news.Containts = model.Content;
            //news.CategoryId = categoryID;
            if (!String.IsNullOrEmpty(model.ImagePath)) 
            {
                if (!String.IsNullOrEmpty(news.ImagePath)) 
                {
                    try
                    {
                        FileInfo file = new FileInfo(HttpContext.Current.Server.MapPath(news.ImagePath));
                        if (file.Exists)
                        {
                            file.Delete();
                        }
                    }
                    catch (Exception ex)
                    {

                    }
                }
                news.ImagePath = model.ImagePath;
            }
            news.Categories.Clear();
            foreach (String c in model.SelectedCategories)
            {
                Guid id;
                Guid.TryParse(c, out id);
                if (id != null)
                {
                    Category category = entities.Categories.FirstOrDefault(cat => cat.CategoryId == id);
                    if (category != null)
                    {
                        news.Categories.Add(category);
                    }
                }
            }
            entities.SaveChanges();
        }

        public void Delete(String id){
            DrugStoreEntities entities = new DrugStoreEntities();
            Guid newId = Guid.Empty;
            if (!Guid.TryParse(id, out newId)) {
                throw new Exception("Tin này không tồn tại");
            }
            News news = entities.News.FirstOrDefault(n => n.NewsId == newId);
            if(news== null)
            {
                throw new Exception("Tin này không tồn tại");
            }

            entities.DeleteObject(news);
            entities.SaveChanges();

            if (!String.IsNullOrEmpty(news.ImagePath)) 
            {
                FileInfo file = new FileInfo(HttpContext.Current.Server.MapPath(news.ImagePath));
                if (file.Exists) 
                {
                    file.Delete();
                }
            }
        }
    }    
    #endregion
}